package com.energyfuture.system.utils;

import com.energyfuture.system.config.ScheduledTask;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ScheduledFuture;

;

/**
 * 定时任务工具类
 *
 * @author energyfuture
 */
public class ScheduleUtils {
    private static ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
    private static Map<String, ScheduledFuture<?>> scheduledfutureMap = new HashMap<>();

    static {
        threadPoolTaskScheduler.initialize();
    }

    public static void start(ScheduledTask scheduledTask, String day) {
        //Trigger trigger = new CronTrigger("0 0 0 1/" + day + " * ?");
        Trigger trigger = new CronTrigger("0/"+day+" * * * * ?");
        ScheduledFuture<?> scheduledFuture = threadPoolTaskScheduler.schedule(scheduledTask, trigger);
        scheduledfutureMap.put("task1", scheduledFuture);
    }

    public static void reset(ScheduledTask scheduledTask, String day) {
        Trigger trigger = new CronTrigger("0 0 0 1/" + day + " * ?");
        //先取消任务
        ScheduledFuture<?> scheduledFuture = scheduledfutureMap.get("task1");
        if (scheduledFuture != null && scheduledFuture.isCancelled()) {
            scheduledFuture.cancel(false);
        }
        scheduledfutureMap.remove("task1");
        //然后启动定时任务
        threadPoolTaskScheduler.schedule(scheduledTask, trigger);
        scheduledfutureMap.put("task1", scheduledFuture);
    }
}